package cn.lcsjsxy.yxz.day.Practice.Thread;

//线程同步
public class Practice2 {
    public static void main(String[] args) {

        // 实现一个银行账户类，包含存款和取款方法，要求在多线程环境下保证账户余额的正确性
        //（使用 synchronized 关键字）。

        BankAccount account = new BankAccount(1000);

        // 存款
        Thread depositThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                account.deposit(100);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // 取款
        Thread withdrawThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                account.withdraw(200);
                try {
                    Thread.sleep(150);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //输出
        depositThread.start();
        withdrawThread.start();
    }
}
class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    // 存款方法（同步）
    public synchronized void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("存入: " + amount + ", 余额: " + balance);
        }
    }
    // 取款方法（同步）
    public synchronized void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("取出: " + amount + ", 余额: " + balance);
        } else if (amount > balance) {
            System.out.println("取款失败，余额不足: " + balance);
        }
    }
    public double getBalance() {
        return balance;
    }
}